
package com.aktk.battlenole;

import java.util.ArrayList;
//import com.aktk.battlenole.BoardCellState.State;
import com.aktk.battlenole.GameData.Stages;
import com.aktk.gameelements.GamePlay.Orientation;
import com.aktk.gameelements.GamePlay.SegmentType;
import com.aktk.gameelements.Player;
import com.aktk.gameelements.Ship;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.LinearLayout;

public class SetupGameBoardActivity extends Activity implements BoardManager.OnClickListener {
	final int numRows = 10; // Board Height
	final int numCols = 10; // Board Width
	String playerName;// = new String( "You" );
	GameData game;
	
	LinearLayout gameBoardContainer;
	BoardManager manager;
	ArrayList<ShipCatalog> catalog;
	TextView message;
	Button bDone;
	Button bReset;
	Button bOrientation;
	
	Orientation o;
    ShipCatalog selectedCatalog;
    
    Player currentPlayer;
    

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_setup);
        game = new GameData();
        dataParse();
        
        gameBoardContainer = (LinearLayout)this.findViewById(R.id.gameBoard);
        manager = new BoardManager (10, 10);
        manager.setOnClickListener(this);
        manager.Draw(this, gameBoardContainer);
        
        catalog = new ArrayList<ShipCatalog>();
        catalog.add( new ShipCatalog(1, 2, this));
        catalog.add( new ShipCatalog(2, 3, this));
        catalog.add( new ShipCatalog(3, 4, this));
        catalog.add( new ShipCatalog(4, 5, this));
        
        setupButtons();
        
        o = Orientation.HORIZONTAL;
        selectedCatalog = null;
        message = (TextView)findViewById(R.id.messageLabel);
        if( game.stage == Stages.PLAYER1_SETUP )
        {
        	message.setText("Player 1, select your first ship to place.");
        }
        if( game.stage == Stages.PLAYER2_SETUP )
        {
        	message.setText("Player 2, select your first ship to place.");
        }
        message.setBackgroundColor(Color.parseColor("#90FFFFFF"));
        message.setTextColor(Color.BLACK);
    }

	private void setupButtons() {
		bDone = (Button)findViewById(R.id.ShipOffButton);
        bDone.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v){
                completeSetup();
            }
            
        });
        
        bReset = (Button)findViewById(R.id.ResetShipLocations);
        bReset.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v){
            	for( int a = 0 ; a < catalog.size() ; ++a )
            	{
            		catalog.get(a).Initialize();
            	}
                refreshBoard();
                message.setText("The board has been cleared.  Please select a ship.");
            }
        });
        
        bOrientation = (Button)findViewById(R.id.horizBox);
        bOrientation.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v){
            	if( o == Orientation.HORIZONTAL )
                {
            		o = Orientation.VERTICAL;
            		message.setText("Orientation switched to Vertical.");
                }
                else
                {
                	o = Orientation.HORIZONTAL;
                	message.setText("Orientation switched to Horizontal.");
                }
            }
        });
	}
	
    public void refreshBoard()
    {
		ArrayList<BoardCellState> states = manager.getStates();
		
		for (int index = 0; index < 100; index++)
		{
			states.get(index).setState(SegmentType.NONE, false, Orientation.HORIZONTAL);
		}
		
		for (int a = 0; a < catalog.size(); ++a )
		{
			Ship currentShip = catalog.get(a).s;
			if( currentShip.getUsed() )
			{
				for( int b = 0 ; b < currentShip.getLength() ; ++b )
				{
					int cellNumber = currentShip.getShipCellNumber( b, numCols );
					states.get( cellNumber ).setState(currentShip.getShipSegmentType(b), currentShip.getOrientation());
				}
			}
		}
		manager.setStatus(states);

    }
   
    public void completeSetup() {
    	for( int a = 0 ; a < catalog.size() ; ++a )
    	{
    		if( !catalog.get(a).s.getUsed() ){
    			message.setText("Please place remaining ships.");
    			return;
    		}
    	}
    	currentPlayer = new Player( playerName , 4 , numRows , numCols );
    	for( int a = 0 ; a < catalog.size() ; ++a )
    	{
    		currentPlayer.addShip( catalog.get(a).s.getRow(0) , catalog.get(a).s.getCol(0), catalog.get(a).s.getLength(), catalog.get(a).s.getOrientation());
    	}
    	
    	if( game.numDevices == 2 )
    	{
    		game.p1 = currentPlayer;
    		game.p1.name = "Player1";
    		game.p2 = new Player("Player2" , 4 , numRows , numCols );
    		game.startGame();
    		Intent i = new Intent(SetupGameBoardActivity.this, MultiGameActivity.class);
            startActivity (i);
    	}
    	else
    	{
    		if ( game.stage == Stages.PLAYER1_SETUP )
    		{
        		game.p1 = currentPlayer;
    		}
    		if ( game.stage == Stages.PLAYER2_SETUP )
    		{
    			game.p2 = currentPlayer;
    		}

        		Intent i = new Intent(SetupGameBoardActivity.this, SwitchActivity.class);
        		startActivity (i);
    	}
    }

	@Override
	public void onClick(int row, int column) {
		if( selectedCatalog != null )
		{
			selectedCatalog.PlaceShip(row, column, selectedCatalog.s.getLength() , o);
			for( int a = 0 ; a < catalog.size() ; ++a )
	        {
	        	if( catalog.get(a).s.getUsed() && catalog.get(a) != selectedCatalog )
	        	{
	        		if( selectedCatalog.s.isOverlap(catalog.get(a).s) )
	        		{
	        			message.setText("Two ships cannot overlap.  Please try again.");
	        			selectedCatalog.Initialize();
	        			refreshBoard();
	        			return;
	        		}
	        	}
	        }
			if( outOfBounds(selectedCatalog) )
			{
				message.setText("Ensure the ship remains entirely on the board.");
				selectedCatalog.Initialize();
				refreshBoard();
    			return;
			}
			refreshBoard();
			if( unplacedShipsRemaining() > 0 )
			{
				message.setText( Integer.toString(unplacedShipsRemaining()) + " ships remaining.  Please select another ship.");
			}
			else
			{
				message.setText("All ships have been placed.  Press 'Done' to continue.");
			}
		}
	}
	
	public boolean outOfBounds( ShipCatalog c ) {
		if( c.s.getRow(0) < 0 || c.s.getRow(0) > numRows - 1 )
		{
			return true;
		}
		if( c.s.getCol(0) < 0 || c.s.getCol(0) > numCols - 1 )
		{
			return true;
		}
		if( c.s.getRow(c.s.getLength() - 1) < 0 || c.s.getRow(c.s.getLength() - 1) > numRows - 1 )
		{
			return true;
		}
		if( c.s.getCol(c.s.getLength() - 1) < 0 || c.s.getCol(c.s.getLength() - 1) > numCols - 1 )
		{
			return true;
		}
		return false;
    }
	
	public void dataParse( ) {
		if ( game.stage == Stages.PLAYER1_SETUP )
		{
			currentPlayer = game.getPlayer(1);
			playerName = "Player 1";
		}
		if ( game.stage == Stages.PLAYER2_SETUP )
		{
			currentPlayer = game.getPlayer(2);
			playerName = "Player 2";
		}
    }
	
	public int unplacedShipsRemaining() {
		int unplacedShips = 0;
		for( int a = 0 ; a < catalog.size() ; ++a )
		{
			if ( !catalog.get(a).s.getUsed() )
			{
				++unplacedShips;
			}
		}
		return unplacedShips;
    }

	public class  ShipCatalog{
		BoardManager b;
		LinearLayout ll;
		int l;
		public Ship s;
		TextView t;
		TextView nameLabel;
		public int num;
		int remaining;

		// Default Constructor
		public ShipCatalog( int shipNum, int length , Activity act ) {
			num = shipNum;
			l = length;
			b = new BoardManager( 1 , length );
			ll = (LinearLayout)act.findViewById(getResources().getIdentifier("ship" + Integer.toString(num), "id", "com.aktk.battlenole") );
			b.Draw(act, ll);
			b.setOnClickListener( new BoardManager.OnClickListener() {
				@Override
				public void onClick(int row, int column) {
					selected();
				}
			} );
			t = (TextView)act.findViewById(getResources().getIdentifier("shipCount" + Integer.toString(num), "id", "com.aktk.battlenole") );
			t.setBackgroundColor(Color.parseColor("#90FFFFFF"));
			nameLabel = (TextView)act.findViewById(getResources().getIdentifier("shipName" + Integer.toString(num), "id", "com.aktk.battlenole") );
			nameLabel.setBackgroundColor(Color.parseColor("#90FFFFFF"));
			Initialize();
		}
		
		public void selected(){
			for( int a = 0 ; a < catalog.size() ; ++a )
			{
				catalog.get(a).setShip(false);
			}
			message.setText("Please place the " + getShipName(l) + " on the board.");
			selectedCatalog = this;
			setShip( true );
			
		}
		
		public String getShipName( int length ){
			ArrayList<String> names = new ArrayList<String>();
			names.add( "Empty" );
			names.add( "Patrol" );
			names.add( "Destroyer" );
			names.add( "Cruiser" );
			names.add( "Battleship" );
			names.add( "Aircraft Carrier" );
			
			return names.get(length);
		}
		
		public void setShip( boolean shot ) {
			ArrayList<BoardCellState> states = b.getStates();
			for( int a = 1 ; a < (states.size() - 1) ; ++a )
			{
				states.get(a).setState(SegmentType.MID, shot, Orientation.HORIZONTAL);
			}
			states.get(0).setState(SegmentType.BOW, shot, Orientation.HORIZONTAL);
			states.get(states.size() - 1).setState(SegmentType.STERN, shot, Orientation.HORIZONTAL);
			b.setStatus(states);
	    }
		
		public void Initialize() {
			remaining = 1;
			setShip( false );
			s = new Ship(l);
			nameLabel.setText( getShipName(l) );
			t.setText( Integer.toString(remaining) + " Remaining");
	    }
		
		public void PlaceShip(int row, int column, int len, Orientation o) {
			s = new Ship( row , column, len, o);
			setShip( false );
			remaining = 0;
			t.setText( Integer.toString(remaining) + " Remaining");
	    }
		
	}
}
